

// STA 连接
boolean wifiBegin(String sid, String pass) {


  // 判断密码存在进行连接
  Serial.print(">>>>> WIFI 链接开始 >>");
  tft.println("wifi connection >>>");
  tft.println(">>  " + sid);
  if (pass)
  {
    Serial.print(sid);
    Serial.print(" > ");
    Serial.println(pass);
    WiFi.begin(sid, pass);
  }
  else
  {
    Serial.println(sid);
    WiFi.begin(sid);
  }
  int i = 0;
  while (WiFi.status() != WL_CONNECTED) {
    i++;
    delay(500);
    Serial.print(".");
    tft.print (".");
    if (i > 20) { //10秒后如果还是连接不上，就判定为连接超时
      Serial.println();
      Serial.println("连接超时！请检查网络环境");
      tft.println("conection  timeout");
      break;
      return false;
    }
  }
  Serial.println(".");
  Serial.println("STA WIFI链接完成");
  tft.println("wifi complate");
  // 保存
  //saveWifiStaJsonConf();
  //Serial.println("STA  WIFI保存链接配置完成");
  return true;
}

//关闭连接
void wifiDisconnect() {
  Serial.println (WiFi.isConnected());
  //连接状态断掉连接
  if (WiFi.isConnected())
  {
    WiFi.disconnect(true);
    Serial.println("wifi disconnect..  ");
  }
  else
  {
    Serial.print ("Disconnect >> wifi status > ");
    Serial.println (WiFi.status());
  }
}



// 读取信号内的sid列表 并返回字符串数组
void wifiScan() {

  if (!WiFi.softAPIP())
  {
    return;
  }

  //  Serial.println("Starting WiFi scan...");
  int scanResult = WiFi.scanNetworks();

  if (scanResult == 0) {
    Serial.println(F("No networks found"));

  }
  else if (scanResult > 0) {
    String ssid;
    int32_t rssi;
    uint8_t encryptionType;
    uint8_t* bssid;
    int32_t channel;
    bool hidden;
    DynamicJsonDocument doc(2048);
    for (int8_t i = 0; i < scanResult; i++) {
      WiFi.getNetworkInfo(i, ssid, encryptionType, rssi, bssid, channel, hidden);
      if (!hidden) {
        doc.add(ssid);
      }
      delay(1);
    }
    WIFI_SCAN_JSON = "";
    serializeJson(doc, WIFI_SCAN_JSON);
    doc.clear();
  } else {
    Serial.printf(PSTR("WiFi scan error %d"), scanResult);
  }

}

// 更新链接信息
//void updateWiFiStatus()
//{
//  WIFI_STATUS_STR = "AP 模式当前连接数 " +  String(WiFi.softAPgetStationNum()) + " ";
//  if (WiFi.localIP()) {
//    WIFI_STATUS_STR = WIFI_STATUS_STR + "\n STA 模式 IP 地址为 " + WiFi.localIP().toString() + " ";
//
//    //    doHttpGet();
//    //    unsigned long currentMillis = millis();
//    //    unsigned long connection_time = currentMillis - STA_CONNECTION_TIME;
//    //    WIFI_STATUS_STR = WIFI_STATUS_STR + " 已连 " + connection_time + " 秒 ";
//  }
//
//}
